package com.br.nninn.maps;

import java.util.ArrayList;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.br.nninn.bean.Hotel;
import com.br.nninn.bean.Map;

public class MapsBuilder implements IMapsBuilder {

	@Override
	public String buildMapsURL(JSONObject obj, String latitude, String longitude) {
		
		List<Hotel> list = this.decodeJSON(obj);
		
		String mapHtml = this.buildHtml(list, latitude, longitude);
		
		return mapHtml;
	}

	private String buildHtml(List<Hotel> list, String latitude, String longitude) {
		
		Map m = new Map(latitude, longitude, list);
		
		System.out.println(m.toString());
		
		return m.toString();
	}

	private List<Hotel> decodeJSON(JSONObject obj) {
		
		List<Hotel> hotelList = new ArrayList<Hotel>();
		
		try {
			
			JSONObject response = obj.getJSONObject("HotelListResponse");
			JSONObject list = response.getJSONObject("HotelList");
			JSONArray summary = list.getJSONArray("HotelSummary");
			
			for (int i = 0; i < summary.length(); i++) {
				
				JSONObject tmp = (JSONObject) summary.get(i);
				
				Hotel hotel = new Hotel();
				if (tmp.has("address1")) {
					hotel.setAddress(tmp.getString("address1"));
				}
				if (tmp.has("city")) {
					hotel.setCity(tmp.getString("city"));
				}
				if (tmp.has("postalCode")) {
					hotel.setPostalCode(tmp.getString("postalCode"));
				}
				if (tmp.has("name")) {
					hotel.setName(tmp.getString("name"));
				}
				if (tmp.has("longitude")) {
					hotel.setLongitude(tmp.getString("longitude"));
				}
				if (tmp.has("latitude")) {
					hotel.setLatitude(tmp.getString("latitude"));
				}
				if (tmp.has("hotelRating")) {
					hotel.setHotelRating(tmp.getString("hotelRating"));
				}
				if (tmp.has("proximityDistance")) {
					hotel.setProximityDistance(tmp.getString("proximityDistance"));
				}
				if (tmp.has("locationDescription")) {
					hotel.setLocationDescription(tmp.getString("locationDescription"));
				}
				if (tmp.has("countryCode")) {
					hotel.setCountryCode(tmp.getString("countryCode"));
				}
				if (tmp.has("lowRate")) {
					hotel.setLowRate(tmp.getString("lowRate"));
				}
				if (tmp.has("highRate")) {
					hotel.setHighRate(tmp.getString("highRate"));
				}
				if (tmp.has("shortDescription")) {
					hotel.setShortDescription(tmp.getString("shortDescription"));
				}
				if (tmp.has("stateProvinceCode")) {
					hotel.setStateProvinceCode(tmp.getString("stateProvinceCode"));
				}
				if (tmp.has("airportCode")) {
					hotel.setAirportCode(tmp.getString("airportCode"));
				}
				
				
				hotelList.add(hotel);
			}
		} catch (JSONException e) {
			e.printStackTrace();
		}
		
		return hotelList;
	}

}
